<template>
  <div class="excel-preview-container">
    <!-- 文件上传区域 -->
    <div class="upload-area p-6 border-2 border-dashed rounded-lg text-center hover:bg-gray-50 transition-colors">
      <input 
        type="file" 
        ref="fileInput" 
        accept=".xls,.xlsx" 
        @change="handleFileUpload" 
        class="hidden"
      />
      <button 
        @click="openFileDialog" 
        class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded transition-colors">
        选择 Excel 文件
      </button>
      <p class="mt-2 text-sm text-gray-500">支持 .xls 和 .xlsx 格式</p>
    </div>

    <!-- 文件信息 -->
    <div v-if="fileName" class="mt-4 p-4 bg-gray-50 rounded-lg">
      <div class="flex items-center justify-between">
        <div>
          <p class="font-medium">{{ fileName }}</p>
          <p class="text-sm text-gray-500">{{ formatFileSize(fileSize) }}</p>
        </div>
        <button 
          @click="clearFile" 
          class="text-red-500 hover:text-red-600 transition-colors">
          <i class="fa fa-times"></i>
        </button>
      </div>
    </div>

    <!-- 工作表选择 -->
    <div v-if="sheetNames.length > 0" class="mt-4">
      <div class="flex flex-wrap gap-2">
        <button 
          v-for="(sheetName, index) in sheetNames" 
          :key="index"
          :class="activeSheetIndex === index ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700'"
          @click="changeSheet(index)"
          class="py-1 px-3 rounded transition-colors">
          {{ sheetName }}
        </button>
      </div>
    </div>

    <!-- 表格预览 -->
    <div v-if="currentSheetData.length > 0" class="mt-4 overflow-x-auto shadow-md rounded-lg">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
          <tr>
            <th v-for="(header, index) in headers" :key="index" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              {{ header }}
            </th>
          </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
          <tr v-for="(row, rowIndex) in currentSheetData" :key="rowIndex" class="hover:bg-gray-50 transition-colors">
            <td v-for="(cell, cellIndex) in row" :key="cellIndex" class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
              {{ cell }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 空状态 -->
    <div v-else-if="fileName && currentSheetData.length === 0" class="mt-4 p-6 text-center text-gray-500">
      <i class="fa fa-file-excel-o text-4xl mb-2 text-gray-300"></i>
      <p>所选工作表为空</p>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="mt-4 p-6 text-center">
      <div class="inline-block animate-spin rounded-full h-8 w-8 border-4 border-blue-200 border-t-blue-500"></div>
      <p class="mt-2 text-gray-500">正在解析文件...</p>
    </div>

    <!-- 错误状态 -->
    <div v-if="error" class="mt-4 p-4 bg-red-50 border border-red-200 rounded-lg">
      <p class="text-red-600 font-medium">解析失败</p>
      <p class="text-red-500 text-sm mt-1">{{ error }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as XLSX from 'xlsx';

const fileInput = ref(null);
const fileName = ref('');
const fileSize = ref(0);
const sheetNames = ref([]);
const sheetsData = ref({});
const activeSheetIndex = ref(0);
const headers = ref([]);
const currentSheetData = ref([]);
const loading = ref(false);
const error = ref('');

// 打开文件选择对话框
const openFileDialog = () => {
  fileInput.value.click();
};

// 处理文件上传
const handleFileUpload = async (e) => {
  const file = e.target.files[0];
  if (!file) return;

  loading.value = true;
  error.value = '';

  try {
    fileName.value = file.name;
    fileSize.value = file.size;
    
    const data = await readFileAsync(file);
    const workbook = XLSX.read(data, { type: 'array' });
    
    // 获取所有表名
    sheetNames.value = workbook.SheetNames;
    
    // 解析每个工作表的数据
    const parsedSheets = {};
    sheetNames.value.forEach(sheetName => {
      const worksheet = workbook.Sheets[sheetName];
      const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
      parsedSheets[sheetName] = jsonData;
    });
    
    sheetsData.value = parsedSheets;
    
    // 默认显示第一个工作表
    if (sheetNames.value.length > 0) {
      changeSheet(0);
    }
  } catch (err) {
    console.error('Error parsing file:', err);
    error.value = err.message || '无法解析文件';
  } finally {
    loading.value = false;
  }
};

// 读取文件为 ArrayBuffer
const readFileAsync = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => resolve(e.target.result);
    reader.onerror = (e) => reject(e);
    reader.readAsArrayBuffer(file);
  });
};

// 切换工作表
const changeSheet = (index) => {
  activeSheetIndex.value = index;
  const sheetName = sheetNames.value[index];
  const sheetData = sheetsData.value[sheetName] || [];
  
  if (sheetData.length > 0) {
    // 第一行数据作为表头
    headers.value = sheetData[0];
    // 剩余数据作为表格内容
    currentSheetData.value = sheetData.slice(1);
  } else {
    headers.value = [];
    currentSheetData.value = [];
  }
};

// 清除已选文件
const clearFile = () => {
  fileInput.value.value = '';
  fileName.value = '';
  fileSize.value = 0;
  sheetNames.value = [];
  sheetsData.value = {};
  activeSheetIndex.value = 0;
  headers.value = [];
  currentSheetData.value = [];
  error.value = '';
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
</script>

<style scoped>
.excel-preview-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
</style>  